package com.jnu.textbook;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.jnu.textbook.data.Book;
import com.jnu.textbook.data.DataBank;

import java.util.List;

public class BookFragment extends Fragment {

    public static final int RESULT_CODE_ADD_DATA = 996;//不再需要requestCode

    private List<Book> books;
    private BookFragment.MyRecyclerViewAdapter recyclerViewAdapter;

    private DataBank dataBank;

    ActivityResultLauncher<Intent> launcherAdd = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if(resultCode== RESULT_CODE_ADD_DATA){
                if(null==data)return;//如果没有添加数据就返回
                String title=data.getStringExtra("title");
                int position=data.getIntExtra("position",books.size());
                books.add(position,new Book(title,R.drawable.book_no_name));
                dataBank.saveData();
                recyclerViewAdapter.notifyItemInserted(position);
            }
        }
    });
    ActivityResultLauncher<Intent>  launcherEdit = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if(resultCode== RESULT_CODE_ADD_DATA) {
                if(null==data)return;
                String title = data.getStringExtra("title");
                int position = data.getIntExtra("position", books.size());
                books.get(position).setTitle(title);
                dataBank.saveData();
                recyclerViewAdapter.notifyItemChanged(position);
            }
        }
    });

    public BookFragment() {
        // Required empty public constructor
    }

    public static BookFragment newInstance() {
        BookFragment fragment = new BookFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView=inflater.inflate(R.layout.fragment_book, container, false);
        initData();

        FloatingActionButton fabAdd=rootView.findViewById(R.id.floating_action_button_add);
        fabAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(BookFragment.this.getContext(),EditBookActivity.class);
                intent.putExtra("position",books.size());
                launcherAdd.launch(intent);
            }
        });

        RecyclerView mainRecyclerView = rootView.findViewById(R.id.recycle_view_books);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext());
        mainRecyclerView.setLayoutManager(layoutManager);

        recyclerViewAdapter = new BookFragment.MyRecyclerViewAdapter(getBooks());
        mainRecyclerView.setAdapter(recyclerViewAdapter);

        return rootView;
    }

    public void initData()
    {
        dataBank = new DataBank(BookFragment.this.getContext());
        books= dataBank.loadData();

    }

    public List<Book> getBooks() {
        return books;
    }

    private class MyRecyclerViewAdapter extends RecyclerView.Adapter {
        private final List<Book> books;

        public MyRecyclerViewAdapter(List<Book> books) {
            this.books=books;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.itemlayout, parent, false);

            return new BookFragment.MyRecyclerViewAdapter.ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            BookFragment.MyRecyclerViewAdapter.ViewHolder viewHolder =(BookFragment.MyRecyclerViewAdapter.ViewHolder) holder;
            viewHolder.getImageView().setImageResource(books.get(position).getCoverResourceId());
            viewHolder.getImageView().setImageResource(books.get(position).getCoverResourceId());
            viewHolder.getTextView().setText(books.get(position).getTitle());
        }

        @Override
        public int getItemCount() {
            return books.size();
        }

        private class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
            public static final int CONTEXT_MENU_ID_ADD = 1;
            public static final int CONTEXT_MENU_ID_DELETE = CONTEXT_MENU_ID_ADD+1;
            public static final int CONTEXT_MENU_ID_EDIT = CONTEXT_MENU_ID_ADD+2;

            private final ImageView imageView;
            private final TextView textView;

            public ViewHolder(View itemview) {
                super(itemview);

                this.imageView=itemview.findViewById(R.id.image_view_book_cover);
                this.textView=itemview.findViewById(R.id.text_view_book_title);

                itemview.setOnCreateContextMenuListener(this);//设置上下文菜单监听者
            }

            public ImageView getImageView() {
                return imageView;
            }
            public TextView getTextView() {
                return textView;
            }

            @Override
            public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {//创建生成上下文菜单
                int position = getAdapterPosition();//获取点击位置
                MenuItem menuItemAdd = contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_ADD,CONTEXT_MENU_ID_ADD, R.string.string_add);//创建3个菜单项
                MenuItem menuItemDelete = contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_DELETE,CONTEXT_MENU_ID_DELETE, R.string.string_delete);
                MenuItem menuItemEdit = contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_EDIT,CONTEXT_MENU_ID_EDIT, R.string.string_edit);

                menuItemAdd.setOnMenuItemClickListener(this);//为菜单项添加点击时的响应函数
                menuItemDelete.setOnMenuItemClickListener(this);
                menuItemEdit.setOnMenuItemClickListener(this);
            }

            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {//响应菜单项
                int position = getAdapterPosition();
                Intent intent;
                switch (menuItem.getItemId())
                {
                    case CONTEXT_MENU_ID_ADD:
                        intent = new Intent(BookFragment.this.getContext(),EditBookActivity.class);
                        intent.putExtra("position",position);
                        launcherAdd.launch(intent);
                        break;
                    case CONTEXT_MENU_ID_EDIT:
                        intent = new Intent(BookFragment.this.getContext(),EditBookActivity.class);
                        intent.putExtra("position",position);
                        intent.putExtra("title",books.get(position).getTitle());
                        launcherEdit.launch(intent);
                        break;
                    case CONTEXT_MENU_ID_DELETE:
                        AlertDialog.Builder alertDB = new AlertDialog.Builder(BookFragment.this.getContext());
                        alertDB.setPositiveButton(BookFragment.this.getContext().getResources().getString(R.string.string_confirmation), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                books.remove(position);
                                dataBank.saveData();
                                BookFragment.MyRecyclerViewAdapter.this.notifyItemRemoved(position);
                            }
                        });
                        alertDB.setNegativeButton(BookFragment.this.getContext().getResources().getString(R.string.string_cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        });
                        alertDB.setMessage(BookFragment.this.getContext().getResources().getString(R.string.string_confirm_delete) +books.get(position).getTitle()+"？");
                        alertDB.setTitle(BookFragment.this.getContext().getResources().getString(R.string.hint)).show();
                        break;
                }
                //创建Toast消息浮动窗口
                Toast.makeText(BookFragment.this.getContext(),"点击了"+menuItem.getTitle(),Toast.LENGTH_LONG).show();
                return false;
            }
        }
    }

    private void registerForActivityResult(ActivityResultContracts.StartActivityForResult startActivityForResult) {
    }
}